package com.hylanda.sys.service;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.hylanda.sys.dao.UserRepository;
import com.hylanda.sys.entity.UUser;
import com.hylanda.sys.model.UUserQo;
import com.hylanda.util.MyDES;


@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public UUser findById(Long id) {
    	UUser uUser = userRepository.findOne(id);
        return uUser;
    }

    public UUser create(UUser uUser) {
    	uUser.setPswd(MyDES.encryptBasedDes(uUser.getPswd()+uUser.getEmail()));
        UUser newUUser = userRepository.save(uUser);
        return newUUser;
    }

    public int update(UUser uUser) {
        return userRepository.update(uUser,"id");
    }

    public void delete(Long id) {
        userRepository.delete(UUser.class, id,"id");
    }

    public Page<UUser> findPage(UUserQo uUserQo){
       Pageable pageable = new PageRequest(uUserQo.getPage(), uUserQo.getSize(), new Sort(Sort.Direction.ASC, "id"));
       Map<String, Object> fieldsFilter=new HashMap<String, Object>();
       if(StringUtils.isNotEmpty(uUserQo.getName())){
    	   fieldsFilter.put("email", uUserQo.getName());
       }
//       if(StringUtils.isNotEmpty(uUserQo.getCreatedateStart()))
		
       return userRepository.findPage(pageable, UUser.class, fieldsFilter);
    }
    public UUser findByUsername(String username, String password) {
    	UUser user=userRepository.findByNickname(username);
    	if(user!=null&&user.getPswd().equals(password))
    		return user;
		return null;
	}

//	public List<URole> findByUserId(Long userId) {
//		UUser user=userRepository.findOne(userId);
//		return user.getRoles();
//	}
}
